import json
import requests
from bs4 import BeautifulSoup as bs
from urllib import parse


class JwcMain():
    initurl = 'http://10.5.2.80'

    class PasswdError(Exception):
        pass

    class NotAble(Exception):
        pass

    def islogin(self):
        if not self.mainPageUrl:
            return False
        response = requests.get(self.mainPageUrl)
        if response.url != self.mainPageUrl:
            return False
        else:
            return True

    def get(self, *args, **kwargs):
        if 'headers' in kwargs and isinstance(kwargs['headers'], dict):
            kwargs['headers']['Referer'] = self.mainPageUrl
        else:
            kwargs['headers'] = {'Referer': self.mainPageUrl}
        response = requests.get(*args, **kwargs)
        url = response.url
        if parse.urlsplit(url).path == 'default2.aspx':
            self.login()
            response = self.get(*args, **kwargs)
        return response

    def post(self, url, data, encodeParam = False, *args, **kwargs):
        if(encodeParam):
            data = self.parseparam(data)
        if 'headers' in kwargs and isinstance(kwargs['headers'], dict):
            kwargs['headers']['Referer'] = self.mainPageUrl
        else:
            kwargs['headers'] = {'Referer': self.mainPageUrl}
        if isinstance(data, str):
            kwargs['headers']['Content-Type'] = 'application/x-www-form-urlencoded'
        response = requests.post(url = url, data = data, *args, **kwargs)
        url = response.url
        if parse.urlsplit(url).path == 'default2.aspx':
            self.login()
            response = self.post(data, *args, **kwargs)
        return response

    def __getUserNmae(self, soup):
        self.userName = self.userName = soup.find(id='xhxm').get_text().split(' ')[2]

    def getSoup(self, url):
        response = requests.get(url)
        soup = bs(response.text, 'html5lib')
        return soup

    def parseurl(self, rawurl):
        rawComponent = parse.urlparse(rawurl)
        queryseq = parse.parse_qsl(rawComponent.query)
        query = parse.urlencode(queryseq, encoding = 'gb2312')
        newComponnet = parse.ParseResult(scheme = 'http', netloc = rawComponent.netloc, path = rawComponent.path, query = query,
                                                params = rawComponent.params, fragment = rawComponent.fragment)
        newurl = parse.urlunparse(newComponnet)
        return newurl

    def parseparam(self, rawparam):
        if(isinstance(rawparam, dict) or isinstance(rawparam, list)):
            newparam = parse.urlencode(rawparam, encoding = 'gb2312')
            return newparam

    def getEntrance(self, soup):
        alist = soup('a')
        self.functionEntrace = {}
        for i in alist:
            rawurl = parse.urljoin(self.mainPageUrl, i.attrs['href'])
            self.functionEntrace[i.text] = self.parseurl(rawurl)

    def login(self):
        response = requests.get(self.initurl)
        self.preurl = response.url[0:-13]
        soup = bs(response.text, 'html5lib')
        viewstate = soup.find(attrs={'name': '__VIEWSTATE'}).attrs['value']
        param = {'__VIEWSTATE': viewstate, 'TextBox1': self.settings['login']['username'],
                 'TextBox2': self.settings['login']['passwd']
            , 'RadioButtonList1': '%D1%A7%C9%FA', 'Button1': '+%B5%C7+%C2%BC+'}
        response = requests.post(self.preurl + 'default2.aspx', data=param)
        if (response.url.split('/')[-1] == 'default2.aspx'):
            raise self.PasswdError
        self.mainPageUrl = response.url
        print(self.mainPageUrl)
        soup = self.getSoup(self.mainPageUrl)
        self.__getUserNmae(soup)
        self.getEntrance(soup)

    def __init__(self):
        try:
            r = requests.get(self.initurl)
            r.raise_for_status()
        except:
            print('connection error')
        with open('settings.json') as f:
            try:
                self.settings = json.load(f)
            except:
                print("json file is invalid")
                exit(1)
        if 'login' in self.settings and 'username' in self.settings['login'] and 'passwd' in self.settings['login']:
            pass
        else:
            print('json file is valid')
            exit(1)
        self.login()
        print(self.userName)

    def log(self, msg):
        pass

if __name__ == '__main__':
    a = JwcMain()
    print(a.functionEntrace)


